<?php
/**
 * Created by PhpStorm.
 * User: DaveTang
 * Date: 2020/3/3
 * Time: 15:56
 * 用户信息缓存组件
 */

namespace App\Controller\Component;
use Cake\Controller\Component;
use Cake\Cache\Cache;

class GoodCacheComponent extends Component
{

    public $_cache_config = 'goods';
    public function initialize(array $config)
    {
        parent::initialize($config);
    }

    /**
     * 商品信息
     */
    public function getVal($good_id)
    {
        $key = 'good_' . $good_id;
        $data = Cache::read($key, $this->_cache_config);
        return empty($data) ? $this->createCache($good_id) : $data;
    }

    /**
     * 创建商品缓存
     */
    public function createCache($good_id)
    {
        $key = 'good_' . $good_id;
        $controller = $this->_registry->getController();
        $controller->loadModel('Goods');
        $data = $controller->Goods->find()
            ->where(['id' => $good_id])
            ->first();
        $cache = empty($data) ? null : $data;
        Cache::write($key, $cache, $this->_cache_config);
        return $cache;
    }

    /**
     * 删除商品缓存
     */
    public function deleteCache($good_id)
    {
        $key = 'good_' . $good_id;
        Cache::delete($key, $this->_cache_config);
        return true;
    }

    /**
     * 获取商品列表信息
     */
    public function getList($content_type, $content_id)
    {
        $controller = $this->_registry->getController();
        $controller->loadModel('GoodsContents');
        $controller->loadModel('Goods');
        $key = 'list_' .$content_type.'_'.$content_id;
        $cache = Cache::read($key, $this->_cache_config);
        if(empty($cache)){
            $cache = $controller->GoodsContents->find()
                ->select(['good_id'])
                ->where(['content_type'=>$content_type, 'content_id'=>$content_id])
                ->toArray();
            $data = empty($cache) ? [0] : array_column($cache, 'good_id');
            $cache = $controller->Goods->find()
                ->select(['id'])
                ->where(['status'=>'enabled','id in '=>$data])
                ->toArray();
            $cache = empty($cache) ? [] : array_column($cache, 'id');
        }
        return $cache;
    }


    /**
     * 删除商品列表
     */
    public function deleteList($content_type, $content_id)
    {
        $key = 'list_' . $content_type.'_'.$content_id;
        Cache::delete($key, $this->_cache_config);
        return true;
    }
}